<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Img extends Model
{
    public $fillable = [
        'img', 'common_id', 'common_type', 'created_at', 'updated_at'
    ];

    public function commons()
    {
        return $this->morphTo();
    }

    public function getImgAttribute($img)
    {
        if (!filter_var($img, FILTER_VALIDATE_URL))
            return env('OSS_ENDPOINT') . env('OSS_PREFIX') . $img;
        return $img;
    }

    static public function getById($id)
    {
        $info = self::where([
            ['id', $id] ,
            ['common_id', 0]
        ])->first();
        abort_unless($info, 404, NotFoundHttpException::class );
        return $info;
    }
}
